/**
 * Raft cluster management implementation
 */

#include <xdevice/raft.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>

/* 获取当前时间（毫秒） */
static uint64_t get_current_time_ms() {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000ULL + ts.tv_nsec / 1000000ULL;
}

/* 集群节点结构 */
typedef struct raft_node {
    int node_id;
    char address[256];
    uint16_t port;
    xdevice_node_state_t state;
    uint64_t last_heartbeat;
    uint64_t next_index;
    uint64_t match_index;
    struct raft_node* next;
} raft_node_t;

/* 集群结构 */
typedef struct {
    int cluster_size;
    int current_node_id;
    uint64_t current_term;
    int voted_for;
    raft_node_t* nodes;
    xdevice_node_state_t node_state;
    uint64_t last_heartbeat_time;
    uint64_t election_timeout;
    bool election_in_progress;
    pthread_mutex_t lock;
    bool initialized;
} raft_cluster_t;

static raft_cluster_t g_cluster = {0};

int raft_cluster_init(int node_id, int cluster_size) {
    if (g_cluster.initialized) {
        return 0;
    }
    
    if (pthread_mutex_init(&g_cluster.lock, NULL) != 0) {
        return -1;
    }
    
    g_cluster.cluster_size = cluster_size;
    g_cluster.current_node_id = node_id;
    g_cluster.current_term = 0;
    g_cluster.voted_for = -1;
    g_cluster.nodes = NULL;
    g_cluster.node_state = XDEVICE_NODE_FOLLOWER;
    g_cluster.last_heartbeat_time = 0;
    g_cluster.election_timeout = 500 + (rand() % 500);  // 500-1000ms随机超时
    g_cluster.election_in_progress = false;
    g_cluster.initialized = true;
    
    // 初始化节点列表
    for (int i = 0; i < cluster_size; i++) {
        raft_node_t* node = malloc(sizeof(raft_node_t));
        if (!node) {
            raft_cluster_cleanup();
            return -1;
        }
        
        node->node_id = i;
        snprintf(node->address, sizeof(node->address), "127.0.0.1");
        node->port = 8000 + i;
        node->state = XDEVICE_NODE_FOLLOWER;
        node->last_heartbeat = get_current_time_ms();
        node->next_index = 1;
        node->match_index = 0;
        node->next = g_cluster.nodes;
        g_cluster.nodes = node;
    }
    
    return 0;
}

void raft_cluster_cleanup(void) {
    if (!g_cluster.initialized) {
        return;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    raft_node_t* current = g_cluster.nodes;
    while (current) {
        raft_node_t* next = current->next;
        free(current);
        current = next;
    }
    
    g_cluster.nodes = NULL;
    g_cluster.initialized = false;
    
    pthread_mutex_unlock(&g_cluster.lock);
    pthread_mutex_destroy(&g_cluster.lock);
}

int raft_cluster_get_leader(void) {
    if (!g_cluster.initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    raft_node_t* current = g_cluster.nodes;
    while (current) {
        if (current->state == XDEVICE_NODE_LEADER) {
            int leader_id = current->node_id;
            pthread_mutex_unlock(&g_cluster.lock);
            return leader_id;
        }
        current = current->next;
    }
    
    pthread_mutex_unlock(&g_cluster.lock);
    return -1; // No leader
}

int raft_cluster_set_leader(int node_id) {
    if (!g_cluster.initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    // 首先将所有节点设为follower
    raft_node_t* current = g_cluster.nodes;
    while (current) {
        current->state = XDEVICE_NODE_FOLLOWER;
        current = current->next;
    }
    
    // 设置指定节点为leader
    current = g_cluster.nodes;
    while (current) {
        if (current->node_id == node_id) {
            current->state = XDEVICE_NODE_LEADER;
            pthread_mutex_unlock(&g_cluster.lock);
            return 0;
        }
        current = current->next;
    }
    
    pthread_mutex_unlock(&g_cluster.lock);
    return -1; // Node not found
}

uint64_t raft_cluster_get_term(void) {
    if (!g_cluster.initialized) {
        return 0;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    uint64_t term = g_cluster.current_term;
    pthread_mutex_unlock(&g_cluster.lock);
    
    return term;
}

int raft_cluster_get_node_count(void) {
    return g_cluster.cluster_size;
}

/* ========== Raft核心功能扩展 ========== */

/* 开始选举 */
int raft_cluster_start_election(void) {
    if (!g_cluster.initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    if (g_cluster.election_in_progress) {
        pthread_mutex_unlock(&g_cluster.lock);
        return 0;  // 选举已在进行中
    }
    
    // 增加任期
    g_cluster.current_term++;
    g_cluster.voted_for = g_cluster.current_node_id;
    g_cluster.node_state = XDEVICE_NODE_CANDIDATE;
    g_cluster.election_in_progress = true;
    
    printf("[Raft] 节点 %d 开始选举，任期 %lu\n", 
           g_cluster.current_node_id, g_cluster.current_term);
    
    pthread_mutex_unlock(&g_cluster.lock);
    
    // 模拟向其他节点请求投票
    int votes_received = 1;  // 自己投票给自己
    int majority = (g_cluster.cluster_size / 2) + 1;
    
    // 简化的投票逻辑：假设大多数节点会投票
    if (g_cluster.cluster_size > 1) {
        votes_received += (g_cluster.cluster_size - 1) / 2;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    if (votes_received >= majority) {
        printf("[Raft] 节点 %d 赢得选举，得票 %d/%d\n", 
               g_cluster.current_node_id, votes_received, g_cluster.cluster_size);
        
        g_cluster.node_state = XDEVICE_NODE_LEADER;
        raft_cluster_set_leader(g_cluster.current_node_id);
    } else {
        printf("[Raft] 节点 %d 选举失败，得票 %d/%d\n", 
               g_cluster.current_node_id, votes_received, g_cluster.cluster_size);
        
        g_cluster.node_state = XDEVICE_NODE_FOLLOWER;
    }
    
    g_cluster.election_in_progress = false;
    
    pthread_mutex_unlock(&g_cluster.lock);
    
    return 0;
}

/* 检查是否需要开始选举 */
bool raft_cluster_should_start_election(void) {
    if (!g_cluster.initialized) {
        return false;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    bool should_elect = false;
    uint64_t current_time = get_current_time_ms();
    
    // 如果是跟随者且选举超时，应该开始选举
    if (g_cluster.node_state == XDEVICE_NODE_FOLLOWER && 
        !g_cluster.election_in_progress &&
        (current_time - g_cluster.last_heartbeat_time) > g_cluster.election_timeout) {
        should_elect = true;
    }
    
    pthread_mutex_unlock(&g_cluster.lock);
    
    return should_elect;
}

/* 接收心跳 */
int raft_cluster_receive_heartbeat(int leader_id, uint64_t term) {
    if (!g_cluster.initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    // 如果接收到更高任期的心跳，更新任期并转为跟随者
    if (term > g_cluster.current_term) {
        g_cluster.current_term = term;
        g_cluster.voted_for = -1;
        g_cluster.node_state = XDEVICE_NODE_FOLLOWER;
        
        printf("[Raft] 节点 %d 接收到更高任期 %lu 的心跳，转为跟随者\n", 
               g_cluster.current_node_id, term);
    }
    
    // 如果任期匹配，重置选举超时
    if (term >= g_cluster.current_term) {
        g_cluster.last_heartbeat_time = get_current_time_ms();
        
        // 更新领导者信息
        raft_node_t* current = g_cluster.nodes;
        while (current) {
            if (current->node_id == leader_id) {
                current->state = XDEVICE_NODE_LEADER;
                current->last_heartbeat = g_cluster.last_heartbeat_time;
            } else {
                current->state = XDEVICE_NODE_FOLLOWER;
            }
            current = current->next;
        }
    }
    
    pthread_mutex_unlock(&g_cluster.lock);
    
    return 0;
}

/* 发送心跳（领导者调用） */
int raft_cluster_send_heartbeat(void) {
    if (!g_cluster.initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    
    if (g_cluster.node_state != XDEVICE_NODE_LEADER) {
        pthread_mutex_unlock(&g_cluster.lock);
        return -1;  // 只有领导者可以发送心跳
    }
    
    uint64_t current_time = get_current_time_ms();
    (void)current_time;  // 预留给将来的心跳时间戳功能
    uint64_t term = g_cluster.current_term;
    int leader_id = g_cluster.current_node_id;
    
    pthread_mutex_unlock(&g_cluster.lock);
    
    printf("[Raft] 领导者 %d 发送心跳，任期 %lu\n", leader_id, term);
    
    // 模拟向所有跟随者发送心跳
    // 在真实实现中，这里会通过网络发送
    
    return 0;
}

/* 获取节点状态 */
xdevice_node_state_t raft_cluster_get_node_state(void) {
    if (!g_cluster.initialized) {
        return XDEVICE_NODE_UNKNOWN;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    xdevice_node_state_t state = g_cluster.node_state;
    pthread_mutex_unlock(&g_cluster.lock);
    
    return state;
}

/* 设置节点状态 */
int raft_cluster_set_node_state(xdevice_node_state_t state) {
    if (!g_cluster.initialized) {
        return -1;
    }
    
    pthread_mutex_lock(&g_cluster.lock);
    g_cluster.node_state = state;
    pthread_mutex_unlock(&g_cluster.lock);
    
    return 0;
}
